from fastapi import FastAPI, Request
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from pydantic import BaseModel
from random import choice

# 创建FastAPI实例app。
app = FastAPI()

# 将静态文件目录"./static"挂载到应用程序中，该目录用于存放静态文件。
app.mount("/static", StaticFiles(directory="static"), name="static")

# 初始化Jinja2模板。
templates = Jinja2Templates(directory="static")

# 奖品列表
prizes = []

# 参与者列表
participants = []

# 参与者
class Participant(BaseModel):
    name: str

# 奖品-获奖者
class Prize(BaseModel):
    winner: str
    prize: str


class DatePrize(BaseModel):
    prize: str


@app.get("/")
async def root(request: Request):
    return templates.TemplateResponse("gift.html", {"request": request})

# 添加参与者
@app.post("/participant")
async def add_participant(participant: Participant):
    participants.append(participant)
    return {"message": "添加成功"}

# 抽奖
@app.post("/draw")
async def draw_prize(date_prize: DatePrize):
    if not participants:
        return {"message": "请添加参与者", "code": 0}

    # 随机选择一个参与者作为获奖者
    winner = choice(participants)
    prize = Prize(winner=winner.name, prize=date_prize.prize)
    prizes.append(prize)
    participants.remove(winner)
    return {"message": f"恭喜 {winner.name}, 你抽到了奖品 : {date_prize.prize}!", "code": 1}

# 获取所有获奖者
@app.get("/prizes")
async def get_prizes():
    return {"prizes": [prize.winner for prize in prizes]}

# 获取所有参与者
@app.get("/participants")
async def get_participants():
    return {"participants": [participant.name for participant in participants]}
